package cn.szq.concurrent.thread.pool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

/**
 * @ClassName: Fibonacci
 * @Description:
 * @Author: szq
 * @Date: 2021-09-28 08:21:45
 */
public class Fibonacci extends RecursiveTask<Integer> {

    int n;

    public Fibonacci(int n){
        this.n = n;
    }

    @Override
    protected Integer compute() {
        if (n <= 1){
            return n;
        }
        Fibonacci f1 = new Fibonacci(n-1);
        f1.fork();
        Fibonacci f2 = new Fibonacci(n-2);
        f2.fork();
        return f1.join()  + f2.join();
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        IntStream.rangeClosed(0, 10).forEach(t->{
            ForkJoinTask task = forkJoinPool.submit(new Fibonacci(t));
            try {
                System.out.println(task.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}
